package com.yshebkb.sulp.service;

import com.yshebkb.sulp.config.AppProperties;
import com.yshebkb.sulp.dao.MenuMapper;
import com.yshebkb.sulp.dao.RoleMenuMapper;
import com.yshebkb.sulp.entity.Menu;
import com.yshebkb.sulp.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author yshebkb
 */
@Service
public class MenuService {

    @Autowired
    private AppProperties appProperties;

    @Resource
    private MenuMapper menuMapper;

    @Resource
    private UserService userService;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    public List<Menu> getRootMenus(String username) {

        List<Role> sysRoles = userService.findUserByUsername(username).getRoles();

        Set<String> roleNames = sysRoles.stream().map(Role::getName).collect(Collectors.toSet());
        List<Menu> menus;
        //系统管理员，拥有最高权限
        if (roleNames.contains(appProperties.getSysAdmin())) {
            menus = menuMapper.findAll();
        } else {
            menus = roleMenuMapper.findMenusByRoleIds(sysRoles.stream().map(Role::getId).collect(Collectors.toList()));
        }

        List<Long> permsMenuId = menus.stream().map(Menu::getId).collect(Collectors.toList());
        List<Menu> rootMenus = menuMapper.findMenusByParentId(-1L);
        getChildrenMenu(rootMenus, permsMenuId);

        return rootMenus;
    }

    private void getChildrenMenu(List<Menu> menus, List<Long> permsMenuId) {
        for (Menu menu : menus) {
            if (permsMenuId.contains(menu.getId()) && menu.getType() == 0) {
                List<Menu> children = menuMapper.findMenusByParentId(menu.getId());
                if (children != null && !children.isEmpty()) {
                    ArrayList<Menu> childMenus = new ArrayList<>();
                    for (Menu child : children) {
                        if (permsMenuId.contains(child.getId()) && child.getType() == 0) {
                            childMenus.add(child);
                        }
                    }
                    if (!childMenus.isEmpty()) {
                        getChildrenMenu(childMenus, permsMenuId);
                        menu.setChildren(children);
                    }
                }
            }
        }
    }
}
